package cn.example.vip.mall.file.controller;

import cn.example.vip.mall.file.entity.FileResult;
import cn.example.vip.mall.file.service.FastDFSService;
import cn.example.vip.mall.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CrossOrigin	// 生产环境需要去掉
@RestController
@RequestMapping("/file")
public class FileController {
	
	
	@Autowired
	private FastDFSService fastDFSService;
	
	/**
	 * FastDFS文件上传
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	public RespResult upload(/*@RequestBody 无需带上*/ MultipartFile file){
		FileResult fileResult = fastDFSService.uploadFile(file);
		if(fileResult != null){
			return RespResult.ok(fileResult);
		}
		return RespResult.error();
	}
	
	/**
	 * FastDFS文件下载
	 * */
	@GetMapping("/download/**/{filename}")
	public RespResult download(@PathVariable("filename") String filename,
							   HttpServletRequest httpServletRequest,
							   HttpServletResponse httpResponse) throws IOException {
		httpServletRequest.setCharacterEncoding("utf-8");
		String fileUri;
		Matcher matcher = Pattern.compile("(/file/download/)(.*)").matcher(httpServletRequest.getRequestURI());
		if(matcher.find()){
			fileUri = matcher.group(2);
			System.out.println("接收到的uri" + fileUri);
			byte[] bytes = fastDFSService.downloadFile(fileUri);
			ServletOutputStream servletOutputStream = httpResponse.getOutputStream();
			servletOutputStream.write(bytes);
			servletOutputStream.flush();
			servletOutputStream.close();
			return RespResult.ok();
		}
		
		return RespResult.error();
		
	}
	
}
